package com.fowo.api.common.util;

import lombok.experimental.UtilityClass;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.function.Predicate;

/**
 * 列表相关辅助方法
 */
@UtilityClass
public class ListUtils {
    public <T> String join(CharSequence delimiter, List<T> elements) {
        StringBuilder sb = new StringBuilder();
        for (Object element: elements) {
            if (element != null) {
                String str = element.toString();
                if(StringUtils.hasText(str)) {
                    if (sb.length() > 0) {
                        sb.append(delimiter);
                    }
                    sb.append(str);
                }
            }
        }
        return sb.toString();
    }

    public <T> T find(Iterable<T> iterable, Predicate<T> predicate) {
        for(T item : iterable) {
            if (predicate.test(item)) {
                return item;
            }
        }
        return null;
    }

    public <T> int findIndex(Iterable<T> iterable, Predicate<T> predicate) {
        int index = 0;
        for(T item : iterable) {
            if (predicate.test(item)) {
                return index;
            }
            index++;
        }
        return -1;
    }
}
